export default {
  namespaced: true, // 开启命名空间
  state: {
    cartList: uni.getStorageSync("cartList") || [], // 购物车列表
  },
  getters: {
    getTotal(state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_number, 0);
    },
    getCartList(state) {
      return state.cartList;
    },
    // 全选
    getAllSelectState(state) {
      return state.cartList.every((item) => item.goods_state);
    },
    // 选中的总金额
    getSelectAmount(state) {
      return state.cartList
        .filter((item) => item.goods_state)
        .reduce((sum, item) => sum + item.goods_number * item.goods_price, 0)
        .toFixed(2);
    },
    // 选中的总数量
    getSelectTotal(state) {
      return state.cartList
        .filter((item) => item.goods_state)
        .reduce((sum, item) => (sum += item.goods_number), 0);
    },
  },
  mutations: {
    // 加入购物车
    addToCart(state, goods) {
      // console.log(goods);
      const findGoods = state.cartList.find(
        (item) => item.goods_id === goods.goods_id
      );
      //  判断之前是否存在
      if (findGoods) {
        findGoods.goods_number += goods.goods_number;
      } else {
        state.cartList.push(goods);
      }
      // 保存到本地
      uni.setStorageSync("cartList", state.cartList);
    },
    // 修改商品的状态
    modifyGoodsstate(state, goods) {
      const findGoods = state.cartList.find(
        (item) => item.goods_id === goods.goods_id
      );
      // 判断是否存在
      if (findGoods) {
        findGoods.goods_state = goods.goods_state;
        // 保存到本地
        uni.setStorageSync("cartList", state.cartList);
      }
    },
    // 修改商品的数量
    modifyGoodsNumber(state, goods) {
      const findGoods = state.cartList.find(
        (item) => item.goods_id === goods.goods_id
      );
      // 判断是否存在
      if (findGoods) {
        findGoods.goods_number = goods.goods_number;
        // 保存到本地
        uni.setStorageSync("cartList", state.cartList);
      }
    },
    // 删除商品
    delete_Goods_id(state, goods_id) {
      const findIndex = state.cartList.findIndex(
        (item) => item.goods_id === goods_id
      );
      // 判断是否存在
      if (findIndex > -1) {
        state.cartList.splice(findIndex, 1);
        //   保存到本地
        uni.setStorageSync("cartList", state.cartList);
      }
    },
    // 全选所有商品
    updateAllGoodsState(state, goods_state) {
      state.cartList.forEach((item) => {
        item.goods_state = goods_state;
      });
      // 保存到本地
      uni.setStorageSync("cartList", state.cartList);
    },
  },
};
